<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { searchImagePage } from '@/api/index.js'
import { getSmartPageNumbers, getEllipsisStatus } from '@/utils/pagination.js'

// 获取路由参数
const route = useRoute()
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const searchResults = ref([])
const isLoading = ref(false)
const showSearchResults = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)
const totalCount = ref(0)
const pageSize = 21 // 每页21张图片
const failedImages = ref(new Set()) // 记录加载失败的图片ID

// 监听搜索关键词变化
const handleSearchKeywordChange = () => {
  if (!searchKeyword.value.trim()) {
    showSearchResults.value = false
  }
}

// 搜索方法
const performSearch = async () => {
  if (!searchKeyword.value.trim()) {
    return
  }

  isLoading.value = true
  showSearchResults.value = true
  currentPage.value = 1

  try {
    const response = await searchImagePage({
      page: currentPage.value,
      pageSize: pageSize,
      name: searchKeyword.value.trim()
    })

    if (response && response.code === 200) {
      const data = response.data
      // 确保返回的数据是数组格式
      searchResults.value = Array.isArray(data.records) ? data.records : []
      totalCount.value = data.total || 0
      totalPages.value = Math.ceil(data.total / pageSize) || 1
      

    } else {
      console.error('搜索失败:', response?.msg || '未知错误')
      searchResults.value = []
      totalCount.value = 0
      totalPages.value = 1
    }
    
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
    totalCount.value = 0
    totalPages.value = 1
  } finally {
    isLoading.value = false
  }
}

// 分页方法
const goToPage = async (page) => {
  if (page < 1 || page > totalPages.value) {
    return
  }

  currentPage.value = page
  isLoading.value = true

  try {
    const response = await searchImagePage({
      page: currentPage.value,
      pageSize: pageSize,
      name: searchKeyword.value.trim()
    })

    if (response && response.code === 200) {
      const data = response.data
      // 确保返回的数据是数组格式
      searchResults.value = Array.isArray(data.records) ? data.records : []
      

    } else {
      console.error('分页失败:', response?.msg || '未知错误')
    }
    
  } catch (error) {
    console.error('分页失败:', error)
  } finally {
    isLoading.value = false
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 处理回车键搜索
const handleKeyPress = (event) => {
  if (event.key === 'Enter') {
    performSearch()
  }
}

// 视频加载错误处理
const handleVideoError = (event) => {
  console.error('视频加载失败:', event)
}

// 视频加载成功处理
const handleVideoLoad = () => {
  // 视频加载成功
}

// 图片加载错误处理
const handleImageError = (imageId) => {
  console.error('图片加载失败:', imageId)
  failedImages.value.add(imageId)
}

// 点击图片查看详情
const openImageDetail = (image) => {
  router.push(`/wallpaper/${image.id}`)
}

// 下载图片
const downloadImage = (image) => {
  // 这里可以实现下载功能
}

// 监听路由参数变化，自动执行搜索
onMounted(() => {
  // 检查URL参数中是否有搜索关键词
  const queryKeyword = route.query.q
  if (queryKeyword) {
    searchKeyword.value = queryKeyword
    // 自动执行搜索
    performSearch()
  }
})

// 计算分页显示的页码
const visiblePages = computed(() => {
  return getSmartPageNumbers(currentPage.value, totalPages.value, 5)
})

// 计算省略号状态
const ellipsisStatus = computed(() => {
  return getEllipsisStatus(currentPage.value, totalPages.value, visiblePages.value)
})

// 监听路由参数变化
watch(() => route.query.q, (newQuery) => {
  if (newQuery && newQuery !== searchKeyword.value) {
    searchKeyword.value = newQuery
    currentPage.value = 1
    performSearch()
  }
})
</script>

<template>
    <div class="search-page">
    <!-- 搜索区域 -->
    <div class="app-content-illustrate" :class="{ 'collapsed': showSearchResults }">
      <div class="video-background">
        <video autoplay muted loop class="background-video" @error="handleVideoError" @loadedmetadata="handleVideoLoad" playsinline>
          <source src="/vm4.mp4" type="video/mp4">
          您的浏览器不支持视频标签。
        </video>
        <!-- 备用背景图片 -->
        <div class="fallback-background"></div>
      </div>
      <div class="content-overlay">
        <h1 class="search-title">免费高清壁纸下载!</h1>
        <div class="search-input-group">
          <input 
            v-model="searchKeyword"
            type="text" 
            placeholder="请输入关键字..." 
            class="search-input"
            @keypress="handleKeyPress"
            @input="handleSearchKeywordChange"
          />
          <button 
            @click="performSearch" 
            class="search-button"
            :disabled="isLoading"
          >
            <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="11" cy="11" r="8"></circle>
              <path d="m21 21-4.35-4.35"></path>
            </svg>
          </button>
        </div>
      </div>
    </div>

    <!-- 搜索结果区域 -->
    <div v-if="showSearchResults" class="app-content-dynamic-images">
      <h3 class="section-title">
        搜索结果
      </h3>
      <div class="results-info">
        <p v-if="totalCount > 0">共找到 {{ totalCount }} 张相关壁纸</p>
        <p v-else>未找到相关壁纸</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在搜索中...</p>
      </div>

      <!-- 搜索结果网格 -->
      <div v-else-if="searchResults.length > 0" class="image-grid">
        <div
          v-for="image in searchResults"
          :key="image.id"
          class="image-card"
          @click="openImageDetail(image)"
          v-show="!failedImages.has(image.id)"
        >
          <div class="image-wrapper">
            <img
              :src="image.url"
              :alt="image.name || '壁纸'"
              class="grid-image"
              loading="lazy"
              @error="handleImageError(image.id)"
            />
            <div class="image-overlay">
              <div class="overlay-content">
                <h4 class="image-title">{{ image.name }}</h4>
                <p class="image-description">{{ image.classify || '高清壁纸' }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 无搜索结果 -->
      <div v-else class="no-results">
        <div class="no-results-icon">🔍</div>
        <h3>未找到相关壁纸</h3>
        <p>请尝试其他关键词</p>
      </div>

      <!-- 分页控件 -->
      <div v-if="totalPages > 1" class="pagination">
        <button
          @click="goToPage(currentPage - 1)"
          :disabled="currentPage === 1"
          class="page-btn prev-btn"
        >
          上一页
        </button>

        <div class="page-numbers">
          <!-- 第一页按钮 -->
          <button
            v-if="ellipsisStatus.showStart"
            @click="goToPage(1)"
            class="page-btn"
            :class="{ active: currentPage === 1 }"
          >
            1
          </button>
          
          <!-- 前省略号 -->
          <span v-if="ellipsisStatus.showStart" class="page-ellipsis">...</span>
          
          <!-- 页码按钮 -->
          <button
            v-for="page in visiblePages"
            :key="page"
            @click="goToPage(page)"
            :class="['page-btn', { active: page === currentPage }]"
          >
            {{ page }}
          </button>
          
          <!-- 后省略号 -->
          <span v-if="ellipsisStatus.showEnd" class="page-ellipsis">...</span>
          
          <!-- 最后一页按钮 -->
          <button
            v-if="ellipsisStatus.showEnd"
            @click="goToPage(totalPages)"
            class="page-btn"
            :class="{ active: currentPage === totalPages }"
          >
            {{ totalPages }}
          </button>
        </div>

        <button
          @click="goToPage(currentPage + 1)"
          :disabled="currentPage === totalPages"
          class="page-btn next-btn"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.search-page {

  /*搜索区域*/
  .app-content-illustrate{
    height: calc(100vh - 160px); /* 铺满除了导航栏的区域 */
    position: relative; /* 添加相对定位 */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    overflow: hidden; /* 确保视频不会溢出容器 */
    transition: all 0.5s ease; /* 添加过渡动画 */
    margin-top: 0; /* 确保没有顶部间距 */

    &.collapsed {
      height: 250px; /* 折叠后保留250px高度，与Home页面保持一致 */
    }

    .video-background {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
      z-index: 0; /* 调整z-index */
      margin-top: 0; /* 确保没有顶部间距 */

      .background-video {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover; /* 确保视频覆盖整个容器 */
        object-position: center 30%; /* 视频内容在中间区域居中 */
        z-index: 0; /* 调整z-index */
        min-width: 100%;
        min-height: 100%;
      }

      .fallback-background {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: url("https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&h=400&fit=crop");
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        z-index: -1; /* 在视频后面作为备用 */
        opacity: 0.8;
      }
    }

    /* 搜索容器样式 */
    .content-overlay {
      background: rgba(0, 0, 0, 0.3);
      backdrop-filter: blur(10px);
      padding: 40px 20px;
      border-radius: 20px;
      text-align: center;
      z-index: 10; /* 确保在视频之上 */
      position: relative; /* 添加相对定位 */
      max-width: 800px;
      width: 90%;
      border: 1px solid rgba(255, 255, 255, 0.1);
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
      transition: all 0.5s ease; /* 添加过渡动画 */

      .collapsed & {
        padding: 15px 20px; /* 减少上下内边距 */
        max-width: 500px; /* 进一步缩小宽度 */
        border-radius: 10px; /* 减小圆角 */
      }

      .search-title {
        color: white;
        font-size: 2.5rem;
        font-weight: 700;
        margin-bottom: 30px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
        line-height: 1.2;
        transition: all 0.5s ease;

        .collapsed & {
          font-size: 1.2rem;
          margin-bottom: 8px;
        }
      }

              .search-input-group {
          display: flex;
          gap: 10px;
          max-width: 600px;
          margin: 0 auto;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 50px;
          padding: 5px;
          backdrop-filter: blur(5px);
          border: 1px solid rgba(255, 255, 255, 0.2);
          transition: all 0.5s ease;

          .collapsed & {
            max-width: 400px;
            padding: 3px;
          }

        .search-input {
          flex: 1;
          background: transparent;
          border: none;
          padding: 15px 20px;
          color: white;
          font-size: 1.1rem;
          outline: none;
          transition: all 0.5s ease;

          &::placeholder {
            color: rgba(255, 255, 255, 0.7);
          }

          .collapsed & {
            padding: 8px 15px;
            font-size: 0.9rem;
          }
        }

        .search-button {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border: none;
          border-radius: 50px;
          padding: 15px 25px;
          color: white;
          cursor: pointer;
          transition: all 0.3s ease;
          display: flex;
          align-items: center;
          justify-content: center;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
          }

          &:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
          }

          .search-icon {
            width: 20px;
            height: 20px;
          }

          .collapsed & {
            padding: 8px 15px;

            .search-icon {
              width: 16px;
              height: 16px;
            }
          }
        }
      }
    }
  }

  /* 搜索结果区域样式 */
  .app-content-dynamic-images {
    padding: 30px 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    border-radius: 12px;
    margin: 0 30px 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    min-height: calc(100vh - 250px); /* 调整高度，为折叠的头部留出空间 */

    .section-title {
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 20px;
      text-align: center;
      color: #2c3e50;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;

      &::after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 50%;
        transform: translateX(-50%);
        width: 60px;
        height: 3px;
        background: linear-gradient(90deg, #3498db, #2ecc71);
        border-radius: 2px;
      }
    }

    .results-info {
      text-align: center;
      margin-bottom: 30px;
      
      p {
        color: #666;
        font-size: 1.1rem;
      }
    }

    .loading-container {
      text-align: center;
      padding: 50px 0;
      
      .loading-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 20px;
      }
      
      p {
        color: #666;
        font-size: 1.1rem;
      }
    }

    .image-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      max-width: 1250px;
      margin: 0 auto;

      .image-card {
        width: 100%;
        aspect-ratio: 4/3;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;

        &:hover {
          transform: translateY(-8px) scale(1.02);
          box-shadow: 0 15px 35px rgba(0, 0, 0, 0.25);
        }

        .image-wrapper {
          position: relative;
          width: 100%;
          height: 100%;
          overflow: hidden;

          .grid-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
          }

          .image-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.4) 100%);
            opacity: 0;
            transition: opacity 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;

            .overlay-content {
              text-align: center;
              color: white;
              padding: 20px;

              .image-title {
                font-size: 1.2rem;
                margin-bottom: 10px;
              }

              .image-description {
                font-size: 0.9rem;
                margin-bottom: 15px;
                opacity: 0.8;
              }

              .image-meta {
                display: flex;
                justify-content: space-between;
                margin-bottom: 15px;
                font-size: 0.8rem;

                .category-tag {
                  background: #667eea;
                  padding: 4px 8px;
                  border-radius: 4px;
                }

                .download-count {
                  opacity: 0.8;
                }
              }
            }
          }

          &:hover .image-overlay {
            opacity: 1;
          }

          &:hover .grid-image {
            transform: scale(1.05);
          }
        }
      }
    }

    .no-results {
      text-align: center;
      padding: 50px 0;

      .no-results-icon {
        font-size: 3rem;
        margin-bottom: 20px;
      }

      h3 {
        color: #333;
        font-size: 1.5rem;
        margin-bottom: 10px;
      }

      p {
        color: #666;
        font-size: 1.1rem;
      }
    }

    .pagination {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 10px;
      margin-top: 30px;

      .page-btn {
        padding: 8px 12px;
        border: 1px solid #ddd;
        background: white;
        color: #333;
        cursor: pointer;
        border-radius: 5px;
        transition: all 0.3s ease;

        &:hover {
          background: #667eea;
          color: white;
          border-color: #667eea;
        }

        &.active {
          background: #667eea;
          color: white;
          border-color: #667eea;
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }

      .page-numbers {
        display: flex;
        gap: 5px;
        align-items: center;
      }

      .page-ellipsis {
        padding: 8px 12px;
        color: #666;
        font-weight: 500;
      }
    }
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
}

</style>